package com.tiny.conf.core.factory;

import com.tiny.conf.core.core.TinyConfLocalCacheConf;
import com.tiny.conf.core.core.TinyConfZkConf;
import com.tiny.conf.core.listener.TinyConfListenerFactory;
import com.tiny.conf.core.util.PropUtil;

import java.util.Properties;

public class TinyConfBaseFactory {

    /**
     * init
     *
     * @param envprop
     */
    public static void init(String envprop) {

        String zkaddress = null;
        String zkdigest = null;
        String env = null;


        // env prop
        if (envprop!=null && envprop.trim().length()>0) {
            Properties envPropFile = PropUtil.loadProp(envprop);
            if (envPropFile!=null && envPropFile.stringPropertyNames()!=null && envPropFile.stringPropertyNames().size()>0) {
                for (String key: envPropFile.stringPropertyNames()) {
                    if ("xxl.conf.zkaddress".equals(key)) {
                        zkaddress = envPropFile.getProperty(key);	// replace if envprop not exist
                    } else if ("xxl.conf.zkdigest".equals(key)) {
                        zkdigest = envPropFile.getProperty(key);
                    } else if ("xxl.conf.env".equals(key)) {
                        env = envPropFile.getProperty(key);
                    }
                }
            }
        }


        init(zkaddress, zkdigest, env);
    }



    /**
     * init
     *
     * @param zkaddress
     * @param zkdigest
     * @param env
     */
    public static void init(String zkaddress, String zkdigest, String env) {
        // init
        TinyConfZkConf.init(zkaddress, zkdigest, env);										// init zk client

        TinyConfLocalCacheConf.init();														// init cache
//        TinyConfListenerFactory.addListener(null, new BeanRefreshXxlConfListener());    // listener all key change

    }

    /**
     * destory
     */
    public static void destroy() {
        TinyConfLocalCacheConf.destroy();	// destroy
        TinyConfZkConf.destroy();			// destroy zk client
    }

}
